window.onload = function() { //所有dom元素加载完后执行此代码

	let prowrap = document.querySelector('.seckill-wrap'); //总的外包
	let wrap = prowrap.querySelector('.product-right'); // ul的外包
	let oul = prowrap.querySelector('.producs-list'); //  ul
	let olis = prowrap.querySelectorAll('.producs-list>a>li'); //所有li
	let size = wrap.clientWidth; //获取一下外包div的宽度
	let timer = null;
	let offset = 0;
	let isEnd = null;
	let prevIcon = prowrap.querySelector('.iconbox>div:first-child');
	let nextIcon = prowrap.querySelector('.iconbox>div:last-child');
	//给向后按钮添加点击事件监听
	nextIcon.addEventListener('click', next)
	//给向前按钮添加点击事件监听
	prevIcon.addEventListener('click', prev);

	//给wrap添加鼠标进入事件，清除计时器，不让他自动轮播了
	prowrap.addEventListener('mouseenter', function() {
		clearInterval(timer)
	})

	//给wrap添加鼠标离开事件，重新加载计时器，让他自动轮播
	prowrap.addEventListener('mouseleave', function() {
		addtimer()
	})

	function next(e, auto = false) { //向后轮播图片
		/* 判断
		*/
			console.log(auto);
		if (offset+size<Math.floor(olis.length/4)*size) {
			// let u = size+offset
			offset +=size
			oul.style.transition = 'all 1s'
			oul.style.transform = `translateX(${-offset}px)`;
			// offset = u
		} else {
			
			let u = offset + olis.length%4*size/4
			oul.style.transition = 'all 1s'
			oul.style.transform = `translateX(${-u}px)`;
			nextIcon.style.color = '#d0d0d0';
			isEnd = true;
			if (auto) {
				let timer1 = setTimeout(function() {
					oul.style.transition = 'all 1s'
					oul.style.transform = `translateX(0)`;
					counter = 0
					offset = 0
				}, 2000)
			}
		}
	}

	function prev() { //向前轮播图片
		if (isEnd) {
			console.log('jia');
			offset = offset + olis.length%4*size/4
			isEnd = false
		}
		if (offset>=size) {
			offset-=size
			oul.style.transition = 'all 1s'
			oul.style.transform = `translateX(${-offset}px)`;
			
		} else {
			
			offset=0
			oul.style.transition = 'all 1s'
			oul.style.transform = `translateX(${offset}px)`;
			prevIcon.style.color = '#d0d0d0';
	    }
   }
	function autoplay() { //为了解决回调函数不能传参的为，我们封装一个函数，让他在这执行
		next(event, true)
	}

	function addtimer() { //添加计时器，实现自动轮播
		timer = setInterval(autoplay, 2000)
	}
	addtimer();
}
